跳到主要内容

Map struct 互转

json


{
"type": "UPDATE",
"database": "blog",
"table": "blog",
"data": [
{
"blogId": "100001",
"title": "title",
"content": "this is a blog",
"uid": "1000012",
"state": "1"
}
]
}

type Event struct {
Type string`json:"type"`
Database string`json:"database"`
Table string`json:"table"`
Data []map[string]string`json:"data"`
}

开始使用前,先定义 map 将转化的 struct 结构,即 blog 结构体,如下:
type Blog struct {
BlogId string`mapstructure:"blogId"`
Title string`mapstructrue:"title"`
Content string`mapstructure:"content"`
Uid string`mapstructure:"uid"`
State string`mapstructure:"state"`
}

因为,接下来要用的是 mapstructure 包,所以 struct tag 标识不再是 json,而是 mapstructure。

示例代码如下:

e := Event{}
if err := json.Unmarshal(msg, &e); err != nil {
panic(err)
}

if e.Table == "blog" {
var blogs []Blog

if err := mapstructure.Decode(e.Data, &blogs); err != nil {
panic(err)
}

fmt.Println(blogs)
}

event 的解析和前面的一样,通过 e.Table 判断是是否来自 blog 表的数据,如果是,使用 Blog 结构体解析。接下来通过 mapstructure 的 Decode 完成解析。